<template>
  <div class="container">
    <div class="app-container">
      <el-tree :expand-on-click-node="false" default-expand-all :data="depts" :props="defaultProps">
        <template #default="{ data }">
          <el-row style="width:100%; height:40px" align="middle" type="flex" justify="space-between">
            <span> {{ data.name }} </span>
            <el-col :span="4">
              <span class="manager-name"> {{ data.managerName }} </span>
              <el-dropdown @command="handleCommand(data.id,$event)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon-button" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <add-dept ref="addDept" :current-node-id="currentNodeId" :show-dialog.sync="showDialog" />
  </div>
</template>
<script>
import { deleteDepartment, getDepartmentList } from '@/api/department'
import { translateListToTreeData } from '@/utils/index'
import addDept from './components/add-dept.vue'
export default {

  name: 'Department',
  components: {
    addDept
  },

  data() {
    return {
      depts: [

      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showDialog: false,
      currentNodeId: null
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    async getDepartmentList() {
      const res = await getDepartmentList()
      console.log(res)
      this.depts = translateListToTreeData(res, 0)
      console.log(this.depts)
    },
    handleCommand(id, type) {
      console.log(id, type)
      // 添加子部门
      if (type === 'add') {
        this.currentNodeId = id
        this.showDialog = true
        // 编辑部门
      } else if (type === 'edit') {
        this.currentNodeId = id
        this.showDialog = true
        // 调用子组件身上的获取部门详情的方法（表单渲染）
        // crrentNodeOd null
        // 原因：显示子组件，内部的数据/方法
        // 晚一点调用子组件方法。。。等他完全渲染完成不然会报错
        // 就是延迟一会等渲染完毕以后再调用
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail()
        })
      } else {
        this.$confirm('您确认要删除该部门吗').then(async() => {
          await deleteDepartment(id)
          this.$message.success('删除成功')
          this.getDepartmentList()
        })
      }
    }
  }
}
</script>
<style scoped lang="scss">
.app-container{
  padding: 32px 100px;
  font-size: small;
}
.manager-name{
  width: 80px;
  display: inline-block;
  font-size: small;
}
.el-dropdown-link{
font-size: small;
}

</style>
